package com.yesun.task.pipeline.handler.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yesun.core.util.FileUtils;
import com.yesun.server.mdp.service.client.config.HttpConfig;
import com.yesun.server.mdp.service.client.impl.DefaultClient;
import com.yesun.server.mdp.service.client.impl.http.HttpRequestContext;
import com.yesun.server.mdp.service.client.impl.http.HttpResponseContext;
import com.yesun.task.pipeline.common.Constant;
import com.yesun.task.pipeline.domain.dto.JobDto;
import com.yesun.task.pipeline.domain.dto.TaskDto;
import com.yesun.task.pipeline.handler.Executor;
import com.yesun.task.pipeline.handler.Handler;
import com.yesun.task.pipeline.handler.Loader;
import com.yesun.task.pipeline.worker.ParallelWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingQueue;

//人气榜Handler
@Slf4j
public class HotHandler extends Handler {

    static SimpleDateFormat shortSdf = new SimpleDateFormat("yyyyMMdd");
    static String TODAY = shortSdf.format(Calendar.getInstance().getTime());
    DefaultClient client = new DefaultClient();



    public HotHandler(JobDto jobDto) {
        super(jobDto);
    }

    @Override
    public Loader getLoader() {
        return new Loader() {
            @Override
            public void load(BlockingQueue queue) {

                String url = "https://emappdata.eastmoney.com/stockrank/getAllCurrentList";
                TaskDto taskDto = new TaskDto();
                taskDto.setJobName(jobDto.getJobName());
                taskDto.setName("人气榜采集任务");
                taskDto.setTag(Constant.JOB_TAG_HOT);

                Map<String,String> map = new HashMap<>();
                map.put("url", url);
                map.put("saveTo", "/df_hot/hot_"+ shortSdf.format(new Date()) +".csv");//暂时只支持保存到磁盘
                taskDto.setMap(map);


                //加入MAP_TASK
                ParallelWorker.MAP_TASK.put(taskDto.getName(), taskDto.getJobName());

                queue.offer(taskDto);
                log.info("添加子任务：" + taskDto.getName());

            }
        };
    }

    @Override
    public Executor getExecutor() {
        return new Executor() {
            @Override
            public void execute(TaskDto taskDto) {
                //执行task的采集
                log.info("execute：" + taskDto.getName());
                HttpConfig config = new HttpConfig(taskDto.getMap().get("url"), HttpConfig.HTTP_METHOD_POST);
                config.setEnctype(HttpConfig.HTTP_ENCTYPE_JSON); //JSON提交
                config.setEncoding("UTF-8");
                HttpRequestContext request = new HttpRequestContext(config);
                request.setParameters("{\"appId\": \"appId01\",\"globalId\": \"786e4c21-70dc-435a-93bb-38\",\"marketType\": \"\",\"pageNo\": 1,\"pageSize\": 100}");

                try {
                    HttpResponseContext response = (HttpResponseContext) client.execute(request);
                    String content = response.getContentAsString();
                    log.debug(content);

                    StringBuffer sb = new StringBuffer("采集日期,股票代码,人气排行,变化\n"); //股价最好从其他表获取
                    JSONArray jsonArray = JSONObject.parseObject(content).getJSONArray("data");
                    jsonArray.stream()
                            .forEach(json -> {
                                sb.append(TODAY + "," + ((JSONObject)json).getString("sc") + "," + ((JSONObject)json).getString("rk") + "," + ((JSONObject)json).getString("rc") + ",\n");
                            });
                    log.info(sb.toString());
                    FileUtils.saveCsv(Constant.BASE_PATH + taskDto.getMap().get("saveTo"), sb.toString(), "UTF-8");
                }catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
    }
}
